<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/public/BaseCms.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/common/StringUtils.php");

class Attachment extends BaseCms
{
    public $tb_name = "attachment";
    private $default_arr = [".jpg", ".jpeg", ".git", ".bmp", ".png"];

    function __construct()
    {
        parent::__construct($this->tb_name);
    }

    /**
     *处理文件上传,成功后将路径返还给前端
     * @param $action
     * @param string $sub_dir
     * @param string $files
     * @param array $include
     */
    function uploadWithoutSave($action, $sub_dir = "", $files = "files", $include = array())
    {
        if ($include == null) {
            $include = array();
        }
        $include = array_merge($include, $this->default_arr);
        /**
         * {
         * "name":"wx_camera_1559523349492.jpg",
         * "type":"image\/jpeg",
         * "tmp_name":"C:\\Users\\l_101\\AppData\\Local\\Temp\\php48BA.tmp",
         * "error":0,
         * "size":291144
         * }
         */
        $redata = ["action" => $action];
        error_log(json_encode($_FILES));
        $temp = $_FILES[$files];
        error_log(json_encode($temp));
        $global_path = APP_PATH . "/" . UPLOAD . "/" . $sub_dir;
        if (!file_exists($global_path)) {
            mkdir($global_path);
        }
        //检查是否存在禁止文件类型
        $flag = false;
        for ($j = 0; $j < count($include); $j++) {
            if (StringUtils::endWith(strtolower($temp["name"]), $include[$j])) {
                $flag = true;
                break;
            }
        }
        if (!$flag && count($include) > 0) {
            throw new ErrorException("非法文件类型:" . $temp["name"]);
        }
        $ext = explode('.', $temp["name"]);
        $sub_path = "/" . UPLOAD . "/" . $sub_dir . "/" . md5($ext[0]) . '.' . $ext[1];
        $uploadfile = APP_PATH . $sub_path;
        $result = move_uploaded_file($temp["tmp_name"], $uploadfile);
        if (!$result) {
            throw new ErrorException("文件" . $temp["name"] . "上传失败");
        }
        $redata["path"] = $sub_path;
        return $redata;
    }

    /**
     * 处理数据上传
     * @param $business_no 业务数据的编号
     * @param string $sub_dir 子目录
     * @param string $files 文件名称
     * @param array $include 包含文件类型
     * @return void
     * @throws ErrorException
     */
    function upload($business_no, $sub_dir = "", $files = "files", $include = array())
    {
        if ($include == null) {
            $include = array();
        }
        $include = array_merge($include, $this->default_arr);
        /**
         * {"files":{"name":["th.jpg","th1.jpg","th2.jpg","th3.jpg"],
         * "type":["image\/jpeg","image\/jpeg","image\/jpeg","image\/jpeg"],
         * "tmp_name":["C:\\Users\\l_101\\AppData\\Local\\Temp\\phpA77F.tmp","C:\\Users\\l_101\\AppData\\Local\\Temp\\phpA780.tmp","C:\\Users\\l_101\\AppData\\Local\\Temp\\phpA781.tmp","C:\\Users\\l_101\\AppData\\Local\\Temp\\phpA782.tmp"],
         * "error":[0,0,0,0],
         * "size":[343225,343430,343785,344774]}}
         */
//        error_log(json_decode(html_entity_decode(stripslashes($_POST["files"])), true));
        $savedFiles = json_decode(html_entity_decode(stripslashes($_POST[$files])), true);
        $ids = array();
        foreach ($savedFiles as $key => $val) {
            $ids[] = $val["idAttachment"];
        }
        $cond = ["business_no" => $business_no];
        if (count($ids) > 0) {
            $cond["id_attachment"] = [$this->param_operation => "nin", $this->param_value_key => implode(",", $ids)];
        }
        parent::delete($cond);
        $global_path = APP_PATH . "/" . UPLOAD . "/" . $sub_dir;
        if (!file_exists($global_path)) {
            mkdir($global_path);
        }
        $file_name = $_FILES[$files]["name"];
//        error_log(json_encode($file_name));
        //$file_type = $_FILES[$files]["type"];
        $file_temp = $_FILES[$files]["tmp_name"];
        //$file_error = $_FILES[$files]["error"];
        $file_size = $_FILES[$files]["size"];
        //检查是否存在禁止文件类型

        $msg = "";
        for ($i = 0; $i < count($file_name); $i++) {
            $name = $file_name[$i];
            $flag = false;
            for ($j = 0; $j < count($include); $j++) {
                if (StringUtils::endWith(strtolower($name), $include[$j])) {
                    $flag = true;
                    break;
                }
            }
            if (!$flag && count($include) > 0) {
                throw new ErrorException("非法文件类型:$$file_name[$type]");
            }
            $ext = explode('.', $name);
            $sub_path = "/" . UPLOAD . "/" . $sub_dir . "/" . md5($ext[0]) . '.' . $ext[1];
            $uploadfile = APP_PATH . $sub_path;
            $result = move_uploaded_file($file_temp[$i], $uploadfile);
            if (!$result) {
                $msg .= "文件" . $file_name[$i] . "上传失败\n";
                continue;
            }
            $data = ["business_no" => $business_no, "file_name" => $name, "file_path" => $uploadfile, "file_size" => $file_size[$i], "download_url" => $sub_path];
            parent::merge(parent::getPrimaryKey(), $data);
        }

        //  error_log($msg);

//        return $uploadfile;
    }
}